package com.huang.foundation.controller;


import com.huang.entity.result.HStringResult;
import com.huang.entity.result.ResultBuilder;
import com.huang.foundation.entity.em.ZoningCodeType;
import com.huang.foundation.entity.po.ZoningCodePO;
import com.huang.foundation.entity.respose.ZoningCodeResponse;
import com.huang.foundation.service.ZoningCodeService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *  行政区划接口控制层
 *
 * @author HuangShen
 * @since 2021-10-16 23:27:44
 */
@RestController
@RequestMapping("/public")
public class ZoningCodeController {
    /**
     * 服务对象
     */
    @Resource
    private ZoningCodeService zoningCodeService;

    @GetMapping("/zonings")
    @ApiOperation(value = "获取行政区域信息")
    private HStringResult<List<ZoningCodeResponse>> zoningCode(@ApiParam("区划类型") @RequestParam("type") String type,
                                     @ApiParam("父级id") @RequestParam(value = "parentId" ,required = false) Long parentId) {

        List<ZoningCodeResponse> zoningCodeResponses = null;
        List<ZoningCodePO> zonings = null;
        ZoningCodeType zoningCodeType = getZoningCodeType(type);
        if (Objects.isNull(zoningCodeType)) return ResultBuilder.failHSingle("参数错误");

        if (StringUtils.equalsIgnoreCase(type, ZoningCodeType.PROVINCE.getCode())) {
            parentId = 0L;
        }
        zonings = this.zoningCodeService.getZonings(zoningCodeType, parentId);

        if (!Objects.isNull(zonings)) {
            zoningCodeResponses = zonings.stream().map(zoningCodePO -> ZoningCodeResponse.builder()
                    .name(zoningCodePO.getName())
                    .parentId(zoningCodePO.getParentId())
                    .value(zoningCodePO.getValue())
                    .build()).collect(Collectors.toList());
            return ResultBuilder.successHSingle(zoningCodeResponses);
        }
        return ResultBuilder.failHSingle("未查询到相关信息");


    }


    private ZoningCodeType getZoningCodeType(String type) {
        ZoningCodeType zoningCodeType = null;
        switch (type) {
            case "PROVINCE": {
                zoningCodeType = ZoningCodeType.PROVINCE;
                break;
            }
            case "CITY": {
                zoningCodeType = ZoningCodeType.CITY;
                break;
            }
            case "COUNTY": {
                zoningCodeType = ZoningCodeType.COUNTY;
                break;
            }
            case "TOWN": {
                zoningCodeType = ZoningCodeType.TOWN;
                break;
            }

        }
        return zoningCodeType;
    }


}

